<template>
	<el-container style="height: 550px; border: 1px solid #eee">
		<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
			<el-scrollbar style="width: 800%">
				<el-input placeholder="Key words to filter" v-model="filterText"></el-input>
				<el-tree
					class="filter-tree"
					:data="fileTree"
					node-key="id"
					:props="defaultProps"
					:filter-node-method="filterNode"
					@node-click="handleNodeClick"
					ref="tree"
					current-node-key="Config/ehcache.xml"
					:default-expanded-keys="expandedCaseUriFolders"
					:default-checked-keys="checkedCaseUris"
				></el-tree>
				<span>
					<el-space wrap>
						<el-button type="text">Download</el-button>
						<el-button type="text">Upload</el-button>
						<el-popconfirm
							confirm-button-text="Yes"
							cancel-button-text="No"
							:icon="InfoFilled"
							icon-color="red"
							title="Are you sure to restore? It will clean up all resources located in your current workspace."
							@confirm="restore"
							@cancel="return"
						>
							<template #reference>
								<el-button type="text">Restore</el-button>
							</template>
						</el-popconfirm>
					</el-space>
				</span>
			</el-scrollbar>
		</el-aside>
		<el-container>
			<el-header height="40px" style="text-align: right; font-size: 12px">
				<span style="white-space: nowrap">
					<el-row>
						<el-input
							style="width: 500px"
							placeholder="http://localhost:3927/restful/cloudtest"
							v-model="endpoint"
						>
							<template #prepend>URL</template>
						</el-input>
						<el-checkbox
							v-model="this.cloudtest.report"
							checked="true"
							label
							size="mini"
							border
							title="If generate report or not?"
						></el-checkbox>
						<el-button
							size="mini"
							type="primary"
							@click="run"
							v-loading.fullscreen.lock="fullscreenLoading"
							:disabled="!this.cloudtest.runnable"
						>Run</el-button>
						<el-button size="mini" type="primary" @click="viewLog">Result</el-button>
						<el-button size="mini" type="primary" @click="viewReport" v-if="this.cloudtest.report">Report</el-button>
					</el-row>
					<div align="left">
						<el-drawer v-model="this.openResultDrawer" title direction="ltr" size="75%">
							<div ref="resultViewer" align="center" class style="height: 100%; width: 100%">
								<el-input v-model="this.cloudtest.result" rows="50" type="textarea" readonly="true" />
							</div>
						</el-drawer>
						<el-drawer v-model="this.openReportDrawer" title direction="ltr" size="75%">
							<!-- <div v-html = "this.iframeHtml" ref="resultViewer" align="center" class style="height: 100%; width: 100%;">
							</div>-->
							<iframe
								name="iframeMap"
								id="iframeMapViewComponent"
								width="100%"
								height="100%"
								:src="this.cloudtest.reportUrl"
								frameborder="0"
								scrolling="yes"
								ref="iframeDom"
							></iframe>
						</el-drawer>
					</div>
				</span>
			</el-header>

			<el-main>
				<el-dialog title="New" v-model="dialogFormVisible">
					<el-form :model="dialogForm">
						<el-form-item label="File Name" label-width="120px">
							<el-input v-model="dialogForm.newFileName" autocomplete="off"></el-input>
						</el-form-item>
					</el-form>
					<template #footer>
						<span class="dialog-footer">
							<el-button @click="dialogFormVisible = false">Cancle</el-button>
							<el-button type="primary" @click="newFileOperation">Confirm</el-button>
						</span>
					</template>
				</el-dialog>
				<br v-if="this.userAgent.indexOf('Windows') < 0" />
				<div style="white-space: nowrap">
					<el-dropdown
						size="mini"
						split-button
						type="primary"
						@click="save"
						title="operations for test case resources"
					>
						Save
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item
									@click="
										this.dialogFormVisible = true;
										this.dialogForm.operation = 'newfolder';
									"
								>New Folder</el-dropdown-item>
								<el-dropdown-item
									@click="
										this.dialogFormVisible = true;
										this.dialogForm.operation = 'newfile';
									"
								>New File</el-dropdown-item>
								<el-popconfirm
									confirm-button-text="Yes"
									cancel-button-text="No"
									:icon="InfoFilled"
									icon-color="red"
									title="Are you sure to delete this?"
									@confirm="delete"
									@cancel="return"
								>
									<template #reference>
										<el-dropdown-item>Delete</el-dropdown-item>
									</template>
								</el-popconfirm>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
					<el-select
						v-model="this.cloudtest.cases"
						multiple
						collapse-tags
						style="margin-left: 5px; width: 150px"
						placeholder="Select Cases..."
						size="small"
						clearable
					>
						<el-option
							v-for="item in this.cloudtest.caseList"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
					<b>@/{{ this.cloudtest.caseUri }}</b>
				</div>
				<div ref="container" class style="position: absolute; height: 80%; width: 82%"></div>
			</el-main>
		</el-container>
	</el-container>
</template>

<script>
import * as monaco from 'monaco-editor';
import editorApi from '/@/api/cloudtest/editor.ts';
import { ElMessage } from 'element-plus';

let editor = null;
export default {
	watch: {
		filterText(val) {
			this.$refs.tree.filter(val);
		},
	},
	computed: {
		expandedCaseUriFolders() {
			let index = this.cloudtest.caseUri.lastIndexOf('/');
			let expands = [];

			if (index > 0) {
				expands.push(this.cloudtest.caseUri.substring(0, index));
			} else {
				expands.push(this.cloudtest.caseUri);
			}
			return expands;
		},
		checkedCaseUris() {
			let checked = [];
			checked.push(this.cloudtest.caseUri);

			return checked;
		},
	},
	methods: {
		newFileOperation() {
			if (this.dialogForm.operation == 'newfolder') {
				this.newFolder();
			} else if (this.dialogForm.operation == 'newfile') {
				this.newFile();
			} else {
				ElMessage.error({
					message: 'Unsupport operation for' + this.dialogForm.operation,
					type: 'error',
				});
			}
		},
		refreshFileTree() {
			editorApi.getFileTree().then((response) => {
				this.fileTree = response.data;
			});
		},

		filterNode(value, data) {
			if (!value) return true;
			return data.label.indexOf(value) !== -1;
		},
		refreshEditorContent() {
			this.cloudtest.content = editor.getValue();
		},
		run_() {
			const loading = this.$loading({
				lock: true,
				text: 'Running in process, Please wait ...',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)',
			});

			editorApi.run(this.cloudtest).then((response) => {
				loading.close();
				if (response.status) {
					ElMessage.success({
						message: 'Run Success',
						type: 'success',
					});
					this.cloudtest.result = response.data.result;
					this.cloudtest.reportUrl = response.data.reportUrl;

					this.refreshFileTree();
				} else {
					ElMessage.error({
						message: 'Operation faild: caused by ' + response.message,
						type: 'error',
					});
				}
			});
			this.refreshFileTree();
		},
		run() {
			this.refreshEditorContent();
			editorApi
				.saveFile(editor.getValue(), this.cloudtest.caseUri)
				.then((response) => {
					this.run_();
				}).catch((error) => {
					console.log(error);
					this.run_();
				});
		},
		viewLog() {
			this.openResultDrawer = true;
		},
		viewReport() {
			//this.iframeHtml = `${import.meta.env.VITE_API_URL}`+this.cloudtest.reportUrl;
			//alert(this.iframeHtml);
			this.openReportDrawer = true;

			let iframe = document.getElementById('iframeMapViewComponent');
			if (iframe != null) {
				iframe.contentWindow.location.reload(true);
			}
		},
		save() {
			this.refreshEditorContent();
			editorApi.saveFile(editor.getValue(), this.cloudtest.caseUri).then((response) => {
				if (response.status) {
					ElMessage.success({
						message: 'Save Success',
						type: 'success',
					});
					this.refreshFileTree();
				} else {
					ElMessage.error({
						message: 'Operation faild: caused by ' + response.message,
						type: 'error',
					});
				}
			});
		},
		newFolder() {
			//alert('newFolder done');
			editorApi.newFolder(this.cloudtest.caseUri + '/' + this.dialogForm.newFileName).then((response) => {
				if (response.status) {
					ElMessage.success({
						message: 'New Folder Success',
						type: 'success',
					});
					this.refreshFileTree();
				} else {
					ElMessage.error({
						message: 'New Folder caused by ' + response.message,
						type: 'error',
					});
				}
			});
			this.dialogFormVisible = false;
		},
		newFile() {
			editorApi.newFile(this.cloudtest.caseUri + '/' + this.dialogForm.newFileName).then((response) => {
				if (response.status) {
					ElMessage.success({
						message: 'New File Success',
						type: 'success',
					});
					this.refreshFileTree();
				} else {
					ElMessage.error({
						message: 'New file failed, caused by ' + response.message,
						type: 'error',
					});
				}
			});
			this.dialogFormVisible = false;
		},
		delete() {
			editorApi.deleteFile(this.cloudtest.caseUri).then((response) => {
				if (response.status) {
					ElMessage.success({
						message: 'Delete File Success',
						type: 'success',
					});
					this.refreshFileTree();
				} else {
					ElMessage.error({
						message: 'Delete File caused by ' + response.message,
						type: 'error',
					});
				}
			});
		},

		handleNodeClick() {
			let res = this.$refs.tree.getCurrentNode();
			this.cloudtest.caseUri = res.id;

			if (res.leaf) {
				editorApi.loadFile(res.id).then((response) => {
					editor.setValue(response.data.content);
					this.cloudtest.caseList = response.data.caseList;
					this.cloudtest.cases = [];
					this.cloudtest.runnable = response.data.runnable;
				});
				editor.updateOptions({ readOnly: false });
			} else {
				editor.setValue('');
				editor.updateOptions({ readOnly: true });
				this.cloudtest.caseList = [];
				this.cloudtest.cases = [];
				this.cloudtest.runnable = true;
			}
		},
		restore(){
			const loading = this.$loading({
				lock: true,
				text: 'Restore in process, Please wait ...',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			editorApi.restore().then((response) => {
				loading.close();
				if (response.status) {
					ElMessage.success({
						message: 'Restore Success',
						type: 'success',
					});
					this.refreshFileTree();
				} else {
					ElMessage.error({
						message: 'Operation faild: caused by ' + response.message,
						type: 'error',
					});
				}
			});
		},
	},
	destroied() {
		editor.dispose();
	},
	unmounted() {
		editor.dispose();
	},
	mounted() {
		editor = monaco.editor.create(this.$refs.container, {
			value: '',
			automaticLayout: true,
			language: 'xml',
		});

		editorApi.getFileTree().then((response) => {
			this.fileTree = response.data;
		});
	},
	data() {
		return {
			cloudtest: {
				caseUri: '',
				content: '',
				report: 'true',
				caseList: [],
				cases: '',
				result: '',
				reportUrl: '',
				runnable: false,
			},
			iframeHtml: ``,
			openResultDrawer: false,
			openReportDrawer: false,
			endpoint: 'http://localhost:3927/restful/cloudtest',
			filterText: '',
			fileTree: [],
			defaultProps: {
				children: 'children',
				label: 'label',
			},
			dialogFormVisible: false,
			dialogForm: {
				newFileName: '',
				operation: '',
			},
			userAgent: navigator.userAgent,
		};
	},
};
</script>
<style>
.el-header {
	background-color: #f1f3f7;
	color: #333;
	line-height: 60px;
}

.el-aside {
	color: #333;
}
</style>
